// sync.Mutex
package main

import (
	"fmt"
	"sync"
	"time"
)

func test1() {
	counter := 0
	for i := 0; i < 5000; i++ {
		go func() {
			counter++
		}()
	}
	time.Sleep(1 * time.Second)
	fmt.Println(counter)
}

func test2() {
	var mu sync.Mutex // 使用互斥锁保护计数器
	counter := 0      //计数器初始值
	for i := 0; i < 5000; i++ {
		go func() {
			defer func() {
				mu.Unlock() //释放互斥锁
			}()
			mu.Lock() //添加互斥锁
			counter++
		}()
	}
	time.Sleep(1 * time.Second)
	fmt.Println(counter)
}

func test3() {
	var mu sync.Mutex
	var wg sync.WaitGroup
	counter := 0
	for i := 0; i < 5000; i++ {
		wg.Add(1)
		go func() {
			defer func() {
				mu.Unlock()
			}()
			mu.Lock()
			counter++
			wg.Done() //结束阻塞等待
		}()
	}
	wg.Wait() //开始阻塞等待
	fmt.Println(counter)
}

func main() {
	//test1()
	//test2()
	test3()
}
